<template>
  <div class="count-down">
    <slot
      :day="dhmsm.day"
      :hour="dhmsm.hour"
      :minute="dhmsm.minute"
      :second="dhmsm.second"
      :millisecond="dhmsm.millisecond"
    >{{ dhmsm.hour }}--{{ dhmsm.minute }}--{{ dhmsm.second }}--{{ dhmsm.millisecond }}</slot>
  </div>
</template>
<script>
const DMS = 1000 * 3600 * 24 // 一天有多少毫秒
const HMS = 1000 * 3600 // 一小时有多少毫秒
const MMS = 1000 * 60 // 一分钟有多少毫秒
const SMS = 1000 // 一秒有多少毫秒
export default {
  name: 'CountDown',
  props: {
    milliseconds: {
      default: 0, // 剩余毫秒数
    },
    interval: {
      default: 1000, // 间隔多少毫秒计算一次剩余毫秒数
    },
    onEnd: {
      type: Function,
      default() {
        console.log('倒计时结束')
      },
    },
  },
  data() {
    return {
      deadline: Date.now() + this.milliseconds, // 到期时间戳
      remain: this.milliseconds, // 剩余毫秒数
    }
  },
  mounted() {
    const fun = () => {
      this.remain = this.deadline - Date.now()
      if (this.remain < 0) {
        this.remain = 0
        this.onEnd()
      } else {
        this.timer = setTimeout(fun, this.interval)
      }
    }
    fun()
  },
  destroyed() {
    clearTimeout(this.timer)
  },
  computed: {
    dhmsm() {
      let ms = this.remain
      let day = Math.floor(ms / DMS)
      ms -= day * DMS
      let hour = Math.floor(ms / HMS)
      ms -= hour * HMS
      let minute = Math.floor(ms / MMS)
      ms -= minute * MMS
      let second = Math.floor(ms / SMS)
      ms -= second * SMS
      let millisecond = ms
      return { day, hour, minute, second, millisecond }
    },
  },
}
</script>
<style lang="scss" scoped></style>
